// 语音监听接口
// 基于串口通信
#include <stdio.h>
#include "control.h"
#include "uart_tool.h"
#include "pthread.h"
#include "msg_queue.h"
#include "global.h"

int serial_fd = -1;

static int voice_init(void)
{
    // 打开串口
    serial_fd = myserialOpen(SERIAL_DEV, BAUD);

    return serial_fd;
}

static void voice_final(void)
{
    if (-1 != serial_fd)
    {
        // 关闭串口
        close(serial_fd);
        serial_fd = -1;
    }
}

// 接受语音指令
static void *voice_get(void *arg)
{
    // 数据类型：0xAA 0x55 0x?? 0x?? 0x55 0xAA
    unsigned char buffer[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    int len = 0;
    mqd_t mqd = -1;
    ctr_info_t *ctr_info = NULL;

    // 解析由主线程传递的数据
    if (NULL != arg)
    {
        ctr_info = (ctr_info_t *)arg;
    }

    if (NULL != ctr_info)
    {
        mqd = ctr_info->mqd;
    }

    if (-1 == serial_fd)
    {
        // 再次尝试打开串口
        voice_init();
        if (-1 == serial_fd)
        {
            printf("open serial failed\n");
            pthread_exit(NULL);
        }
    }

    printf("%s|%s|%d\n", __FILE__, __func__, __LINE__);
    // 不停获取串口传递过来的数据
    while (1)
    {
        memset(buffer, 0x00, sizeof(buffer));
        len = serial_getString(serial_fd, buffer);
        printf("%s|%s|%d:0x%x,0x%x,0x%x,0x%x,0x%x,0x%x\n", __FILE__, __func__, __LINE__, buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
        if (len > 0)
        {
            // 符合数据格式再进行处理
            if (buffer[0] == 0xAA && buffer[1] == 0x55 && buffer[4] == 0x55 && buffer[5] == 0xAA)
            {
                printf("%s|%s|%d\n", __FILE__, __func__, __LINE__);
                // 发送数据给消息队列，让消息队列处理
                msg_queue_send(mqd, buffer, len);
            }
        }
    }

    pthread_exit(NULL);
}

// 语音播报
static void *voice_set(void *arg)
{
    unsigned char *buffer = (unsigned char *)arg;

    if (-1 == serial_fd)
    {
        // 再次尝试打开串口
        voice_init();
        if (-1 == serial_fd)
        {
            printf("open serial failed\n");
            pthread_exit(NULL);
        }
    }

    // 创建线程后，将线程分离
    pthread_detach(pthread_self());

    if (NULL != buffer)
    {
        printf("%s|%s|%d:0x%x,0x%x,0x%x,0x%x,0x%x,0x%x\n", __FILE__, __func__, __LINE__, buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
        // 发送数据给串口 语音模块接受到串口数据会进行语音播报
        serial_sendString(serial_fd, buffer, 6);
    }

    pthread_exit(NULL);
}

struct control voice_control =
    {
        .control_name = "voice",
        .init = voice_init,
        .final = voice_final,
        .get = voice_get,
        .set = voice_set,
        .next = NULL};

// 将语音监听加入链表
struct control *add_voice_to_control(struct control *phead)
{
    return add_interface_to_control_list(phead, &voice_control);
}